package com.moon.admin.tools.servcie;

import com.moon.admin.framework.config.SystemConfig;
import com.moon.admin.framework.springmvc.config.SpringContextConfig;
import com.moon.admin.tools.domain.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 利用tail命令获取服务器上的日志实时显示在网页上
 * @author moon
 */
@Slf4j
public class ServerLogSerice implements Runnable {

  private Session session;
  private Message message;
  private CountDownLatch countDownLatch;

  public ServerLogSerice(Session session, Message message, CountDownLatch countDownLatch) {
    this.session = session;
    this.message = message;
    this.countDownLatch = countDownLatch;
  }

  @Override
  public void run() {
    SystemConfig siteConfig = SpringContextConfig.getBean(SystemConfig.class);
      Process process = null;
      BufferedReader br = null;
      try {
        String command = "tail -200f " + siteConfig.getServerlog();
        process = Runtime.getRuntime().exec(command);
        br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")));
        String line;
        while ((line = br.readLine()) != null) {
          try {
            session.getBasicRemote().sendObject(new Message(message.getType(), line));
          } catch (Exception e) {
            log.error("type: {}, thread: {}, channel close error: {}", message.getType(), this.getClass().getName(),
                e.getMessage());
            break;
          }
        }
      } catch (Exception e) {
        log.error("sendMessage error: {}", e.getMessage());
      } finally {
        try {
          if (br != null) {
            br.close();
          }
          if (process != null) {
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
            process.waitFor();
            Thread.sleep(1000);
            process.destroy();
          }
          if (countDownLatch != null) {
            countDownLatch.countDown();
          }
        } catch (IOException | InterruptedException e) {
          e.printStackTrace();
        }
      }
  }
}
